<template>
	<div class="base-info-page">
		<NavHeader
			:title="t('circuit.title', '电路信息')"
			:showStepProgress="true"
			:current="3"
		/>
		<div class="info-card-group">
			<!-- 主电箱 -->
			<div class="info-card photo-card">
				<div class="photo-header">
					<span class="card-label">{{
						t('circuit.mainBox', '主电箱')
					}}</span>
				</div>
				<div class="photo-row">
					<van-uploader
						v-model="form.mainBoxPhotos"
						:max-count="3"
						multiple
						:before-read="beforeRead"
						:after-read="(file) => afterRead(file, 'mainBox')"
						:deletable="true"
						preview-size="97"
					>
						<template #default>
							<div class="upload-area">
								<van-icon
									name="photograph"
									size="24"
									color="#B1B1B2"
								/>
							</div>
						</template>
					</van-uploader>
					<van-uploader
						v-model="form.mainBoxPhotos"
						:max-count="3"
						multiple
						:before-read="beforeRead"
						:deletable="true"
						preview-size="97"
						style="display: none"
					/>
					<van-uploader
						v-model="form.mainBoxPhotos"
						:max-count="3"
						multiple
						:before-read="beforeRead"
						:deletable="true"
						preview-size="97"
						style="display: none"
					/>
					<van-uploader
						v-model="form.mainBoxPhotos"
						:max-count="3"
						multiple
						:before-read="beforeRead"
						:deletable="true"
						preview-size="97"
						style="display: none"
					/>
				</div>
				<span class="photo-tip">{{
					t(
						'circuit.mainBoxTip',
						'需拍摄到最内侧开关，用于评估电力供应情况。'
					)
				}}</span>
			</div>
			<!-- 电表 -->
			<div class="info-card photo-card">
				<div class="photo-header">
					<span class="card-label">{{
						t('circuit.meter', '电表')
					}}</span>
				</div>
				<div class="photo-row">
					<van-uploader
						v-model="form.meterPhotos"
						:max-count="3"
						:before-read="beforeRead"
						:after-read="(file) => afterRead(file, 'meter')"
						:deletable="true"
						preview-size="97"
					>
						<template #default>
							<div class="upload-area">
								<van-icon
									name="photograph"
									size="24"
									color="#B1B1B2"
								/>
							</div>
						</template>
					</van-uploader>
				</div>
			</div>
			<!-- 电线预留及周边环境 -->
			<div class="info-card photo-card">
				<div class="photo-header">
					<span class="card-label">{{
						t('circuit.wire', '电线预留及周边环境')
					}}</span>
				</div>
				<div class="photo-row">
					<van-uploader
						v-model="form.wirePhotos"
						:max-count="9"
						:before-read="beforeRead"
						:after-read="(file) => afterRead(file, 'wire')"
						:deletable="true"
						preview-size="97"
					>
						<template #default>
							<div class="upload-area">
								<van-icon
									name="photograph"
									size="24"
									color="#B1B1B2"
								/>
							</div>
						</template>
					</van-uploader>
				</div>
			</div>
			<!-- 配电箱到smart panel的距离（视频） -->
			<div class="info-card photo-card">
				<div class="photo-header">
					<span class="card-label">{{
						t('circuit.distance', '配电箱到smart panel的距离')
					}}</span>
				</div>
				<div class="photo-row">
					<van-uploader
						v-model="form.distanceVideo"
						:max-count="1"
						:before-read="beforeVideoRead"
						:after-read="(file) => afterRead(file, 'video')"
						:deletable="true"
						accept="video/*"
						preview-size="125"
					>
						<template #default>
							<div class="upload-area video">
								<van-icon
									name="video"
									size="24"
									color="#B1B1B2"
								/>
							</div>
						</template>
					</van-uploader>
				</div>
				<span class="photo-tip">{{
					t(
						'circuit.distanceTip',
						'请拍摄或上传一段视频，帮助技术人员评估安装难度和所需材料'
					)
				}}</span>
			</div>
		</div>
		<!-- //占空间 -->
		<div style="height: 100px"></div>
		<div class="bottom-btn-bar">
			<button class="btn-prev" @click="onPrev">
				{{ t('common.prev', '上一步') }}
			</button>
			<button class="btn-next" @click="onSubmit">
				{{ t('circuit.submit', '提交信息') }}
			</button>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { showFailToast, showToast } from 'vant'
import NavHeader from '@/components/NavHeader.vue'
import { uploadFile } from '@/api/user'
import { useOrderStore } from '@/stores/order'
import { getOrderDetailApi, submitOrderApi } from '@/api/user'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

const form = ref({
	mainBoxPhotos: [] as any[],
	meterPhotos: [] as any[],
	wirePhotos: [] as any[],
	distanceVideo: [] as any[],
})

const orderStore = useOrderStore()
const route = useRoute()
const router = useRouter()

onMounted(async () => {
	// 回显
	form.value.mainBoxPhotos = (orderStore.customer.master_images || []).map(
		(url) => ({ url })
	)
	form.value.meterPhotos = (
		orderStore.customer.electricity_meter_images || []
	).map((url) => ({ url }))
	form.value.wirePhotos = (orderStore.customer.environment_images || []).map(
		(url) => ({ url })
	)
	form.value.distanceVideo = orderStore.customer.video
		? [{ url: orderStore.customer.video }]
		: []
})

const beforeRead = (file: File | File[]) => {
	const files = Array.isArray(file) ? file : [file]
	for (const f of files) {
		if (!['image/jpeg', 'image/png'].includes(f.type)) {
			showFailToast(t('circuit.onlyJpgPng', '仅支持 JPG/PNG 格式'))
			return false
		}
		if (f.size > 5 * 1024 * 1024) {
			showFailToast(t('circuit.maxSize', '图片大小不能超过15MB'))
			return false
		}
	}
	return true
}
const beforeVideoRead = (file: File | File[]) => {
	const files = Array.isArray(file) ? file : [file]
	for (const f of files) {
		if (!f.type.startsWith('video/')) {
			showFailToast(t('circuit.onlyVideo', '仅支持视频文件'))
			return false
		}
		if (f.size > 150 * 1024 * 1024) {
			showFailToast(t('circuit.maxVideoSize', '视频大小不能超过150MB'))
			return false
		}
	}
	return true
}

const afterRead = async (
	file: any,
	type: 'mainBox' | 'meter' | 'wire' | 'video'
) => {
	const files = Array.isArray(file) ? file : [file]
	for (const f of files) {
		if (!(f.file instanceof Blob)) {
			showFailToast(t('circuit.fileTypeError', '文件类型错误'))
			return
		}
		try {
			const res = await uploadFile({ file: f.file })
			const { basePath, fileName } = res.data
			f.url = basePath + fileName
			f.path = fileName
		} catch (e) {
			showFailToast(t('circuit.uploadFail', '上传失败'))
		}
	}
}

const onPrev = () => window.history.back()
const onSubmit = async () => {
	if (form.value.mainBoxPhotos.length < 1)
		return showFailToast(t('circuit.uploadMainBox', '请上传主电箱照片'))
	if (form.value.meterPhotos.length < 1)
		return showFailToast(t('circuit.uploadMeter', '请上传电表照片'))
	if (form.value.wirePhotos.length < 1)
		return showFailToast(
			t('circuit.uploadWire', '请上传电线预留及周边环境照片')
		)
	if (form.value.distanceVideo.length < 1)
		return showFailToast(
			t('circuit.uploadDistance', '请上传配电箱到smart panel的距离视频')
		)
	// 保存到全局
	orderStore.customer.master_images = form.value.mainBoxPhotos.map(
		(f) => f.url || f.path
	)
	orderStore.customer.electricity_meter_images = form.value.meterPhotos.map(
		(f) => f.url || f.path
	)
	orderStore.customer.environment_images = form.value.wirePhotos.map(
		(f) => f.url || f.path
	)
	orderStore.customer.video =
		form.value.distanceVideo[0]?.url ||
		form.value.distanceVideo[0]?.path ||
		''
	// 提交逻辑
	try {
		const params = {
			order_no: orderStore.order_no,
			customer: { ...orderStore.customer },
		}
		console.log('提交参数', params)
		await submitOrderApi(params)
		showToast(t('circuit.submitSuccess', '提交成功'))
		// 可跳转到成功页
		router.push({
			name: 'OrderSuccess',
		})
	} catch (e) {
		console.log('提交失败', e)
		// showFailToast(t('circuit.networkError', '网络异常，提交失败'))
	}
}
</script>

<style scoped>
.base-info-page {
	background: #f3f4f6;
	min-height: 100vh;
	padding-bottom: 24px;
}

.info-card-group {
	padding: 16px 0 0 0;
	display: flex;
	flex-direction: column;
	gap: 12px;
	align-items: center;
}

.info-card {
	width: 95%;
	max-width: 450px;
	border-radius: 15px;
	background: #fff;
	box-shadow: none;
	margin: 0;
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	border: 1px solid #eee;
	padding: 16px;
	position: relative;
}

.card-label {
	font-size: 16px;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 600;
	color: #000;
	letter-spacing: -0.3px;
}

.photo-header {
	margin-bottom: 12px;
}

.photo-tip {
	display: block;
	font-size: 12px;
	color: #b1b1b2;
	margin-top: 4px;
}

.photo-row {
	display: flex;
	gap: 8px;
	margin-bottom: 8px;
}

.upload-area {
	width: 97px;
	height: 66px;
	background: #f4f4f4;
	border-radius: 15px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.upload-area.video {
	width: 184px;
	height: 125px;
}

:deep(.van-uploader__preview-image) {
	border-radius: 15px;
}

:deep(.van-uploader__preview-delete) {
	background: rgba(0, 0, 0, 0.5);
}

.bottom-btn-bar {
	position: fixed;
	left: 0;
	bottom: 0;
	width: 100vw;
	display: flex;
	justify-content: center;
	align-items: center;
	background: #fff;
	padding: 12px 0 12px 0;
	z-index: 20;
	gap: 16px;
	box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.03);
}

.btn-prev {
	width: 108px;
	height: 60px;
	border-radius: 10px;
	background: #e7e7e7;
	color: #333a44;
	font-size: 20px;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 600;
	border: none;
	outline: none;
	letter-spacing: -0.3px;
	cursor: pointer;
}

.btn-next {
	width: 232px;
	height: 60px;
	border-radius: 10px;
	background: #0065d1;
	color: #fff;
	font-size: 20px;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 600;
	border: none;
	outline: none;
	letter-spacing: -0.3px;
	cursor: pointer;
}
</style>
